<?
/**
 * VoiceOne Settings/Extensions/Cid
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 */

  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");

  //================ XAJAX ================
	function delCidRow($trunk_id){
    global $asterisk,$cwlang;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
		$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
		}
    $script.=" document.getElementById('stats').deleteRow(document.getElementById('".$trunk_id."_row').rowIndex); ";
		$script.=" var optObj=document.createElement('option'); ";
		$script.=" optObj.value='".$trunk_id."'; ";
		$script.=" optObj.innerText='".$trunk_name."'; ";   //cross browser fix
    $script.=" optObj.text='".$trunk_name."'; ";        //cross browser fix
    $script.=" document.getElementById('trunklist').appendChild(optObj); ";
    $script.=" if(document.getElementById('stats').rows.length==1){ ";
    $script.="   var newRow = document.getElementById('stats').insertRow(document.getElementById('stats').rows.length); ";
    $script.="   newRow.id = 'tableintro'; ";
    $script.="   newRow.bgColor = '#ffffff'; ";
    $script.="   var newCell_01 = newRow.insertCell(0); newCell_01.colSpan = '3'; newCell_01.innerHTML = '&nbsp;'; ";
    $script.="   var newCell_234 = newRow.insertCell(1); newCell_234.colSpan = '3'; newCell_234.innerHTML = '".T_("Caller ID is set to default for all lines")."'; ";
    $script.="} ";
    // Return the xajaxResponse object
		$objResponse->addScript($script);
    return $objResponse->getXML();
  }
  function addCid($trunk_id){
    global $asterisk,$relBasePath;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
  	$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
    	$trunk_cidnum=$t["cid_number"];
  		$trunk_cidname=$t["cid_name"];
  		$trunk_force=$t["force_cid"];
  		$truk_clir=$t["clir"];
  		$truk_numbers=$t["cid_list"];
  		if (is_array($truk_numbers))
  	  foreach ($truk_numbers as $number) $trunk_cidlist.="<option value=\"$number\">$number</option>";
		}
    if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
		$cell0="<img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" />";
		$cell1="<input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" />";
		$cell2="$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$trunk_name."\" />";
		$cell3="<select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\" >".$trunk_cidlist."</select>";
		$cell4="<input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$trunk_cidname."\" />";
    //$cell5="<input type=\"checkbox\" id=\"cid[".$trunk_id."][force]\" name=\"cid[".$trunk_id."][force]\" $forceChecked disabled=\"disabled\" />";
    if($forceChecked!="") $cell5="<span style=\"color: red;\"><strong>ON<strong></span>"; else $cell5="<span style=\"color: black;\">OFF</span>";
    // Return the xajaxResponse object
		$objResponse->addAssign($trunk_id."_row_cell0","innerHTML",$cell0);
    $objResponse->addAssign($trunk_id."_row_cell1","innerHTML",$cell1);
    $objResponse->addAssign($trunk_id."_row_cell2","innerHTML",$cell2);
    $objResponse->addAssign($trunk_id."_row_cell3","innerHTML",$cell3);
		$objResponse->addAssign($trunk_id."_row_cell4","innerHTML",$cell4);
    $objResponse->addAssign($trunk_id."_row_cell5","innerHTML",$cell5);
    $objResponse->addScript(" document.getElementById('trunklist').remove(document.getElementById('trunklist').selectedIndex); ");
    $objResponse->addScript(" document.getElementById('stats').deleteRow(document.getElementById('tableintro').rowIndex); ");
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("addCid");
	$xajax->registerFunction("delCidRow");
  $xajax->processRequests();

  //================ POST & GET =================
  if((count($_POST)>0)&&($_POST["extension"]!="")){
    //put cid settings
    $extension_id=$_POST["extension"];
    $cidArr=$_POST["cid"];
    if(is_array($cidArr)){
		  foreach($cidArr as $t){
			  $cid["id"]=0;
				$cid["trunk"]=$t["id"];
				$cid["extension"]=$extension_id;
				if(isset($t["clir"])&&($t["clir"]=="on")){
				  $cid["clir"]=1;
				  $cid["cid_number"]=$t["cidnum"];
				  $cid["cid_name"]=$t["cidname"];
				}else{
				  $cid["clir"]=0;
					$cid["cid_number"]=$t["cidnum"];
					$cid["cid_name"]=$t["cidname"];
				}
				$entry[]=$cid;
			}
      $ret=$asterisk->putCid($extension_id,$entry);
      if($ret>0){
      	$alert="<div class=\"AlertGood\">".T_("Cid options have been saved")."</div>";
        //if extension is a virtual extension erase also the linked clints settings
        $virtualArr=$asterisk->getVirtualExtension($extension_id);
        if((is_array($virtualArr))&&(is_array($virtualArr[0]))&&(is_array($virtualArr[0]["linked_clients"]))){
        	foreach($virtualArr[0]["linked_clients"] as $client){
          	$ret=$asterisk->putCid($client,$entry);
            if($ret<1){
            	$alert="<div class=\"AlertGood\">".T_("Cid options haven't been saved")."</div>";
              break;
            }
          }
        }
      }else $alert="<div class=\"AlertGood\">".T_("Cid options haven't been saved")."</div>";
    }else{
      $ret=$asterisk->delCid(0,$extension_id);
      if($ret>0){
      	$alert="<div class=\"AlertGood\">".T_("Cid options haven't been saved")."</div>";
        //if extension is a virtual extension erase also the linked clints settings
        $virtualArr=$asterisk->getVirtualExtension($extension_id);
        if((is_array($virtualArr))&&(is_array($virtualArr[0]))&&(is_array($virtualArr[0]["linked_clients"]))){
        	foreach($virtualArr[0]["linked_clients"] as $client){
          	$ret=$asterisk->delCid(0,$client);
            if($ret<1){
            	$alert="<div class=\"AlertGood\">".T_("Cid options haven't been saved")."</div>";
              break;
            }
          }  
        }
      }else $alert="<div class=\"AlertGood\">".T_("Cid options have been saved")."</div>";
    }
    //go to main page
    goToMainPage($alert,"../");
  }
  //================ PAGE LOGIC ================
  //get mailboxes
  if((isset($_GET["id"]))&&($_GET["id"]!="")){
    //load cid
    $ret=$asterisk->getClient($_GET["id"],0);
    if(is_array($ret)) $ret=$ret[0];
    else{
    	$ret=$asterisk->getVirtualExtension($_GET["id"]);
      if(is_array($ret)) $ret=$ret[0];
      else{
      	header("location: ../");
      	die();
      } 
    }
    //get CF options
    if(is_array($ret)){
      $extension=$ret["extension"];
      $cidArr=$asterisk->getCid(0,$_GET["id"]);
  	  if(is_array($cidArr)){
        foreach ($cidArr as $c) {
          $trunk_id=$c["trunk"];
    			$clir=$c["clir"];
    			$cidnum=$c["cid_number"];
    			$cidname=$c["cid_name"];
    			$trunkArr=$asterisk->getTrunk($trunk_id,0);
          if(is_array($trunkArr)){
            $t=$trunkArr[0];
            $trunk_name=$t["name"];
        		$truk_numbers=$t["cid_list"];
            $trunk_force=$t["force_cid"];
            $numberslist="";
        		if (is_array($truk_numbers))
        	  foreach ($truk_numbers as $number){
              if($cidnum==$number) $numberslist.="<option value=\"$number\" selected=\"selected\">$number</option>";
              else $numberslist.="<option value=\"$number\">$number</option>";
            }
      		}
          if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
          if($clir==1) $checked="checked=\"checked\""; else $checked="";
      		$cidlist.="<tr id=\"".$trunk_id."_row\" bgcolor=\"#ffffff\">";
        	$cidlist.="<td><img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" /></td>";
        	$cidlist.="<td><input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" $checked /></td>";
        	$cidlist.="<td>$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$cidname."\" /></td>";
          $cidlist.="<td><select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\">".$numberslist."</select></td>";
        	$cidlist.="<td><input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$cidname."\"/></td>";
          if($forceChecked!="") $cidlist.="<td><span style=\"color: red;\"><strong>ON<strong></span></td>"; else $cidlist.="<td><span style=\"color: black;\">OFF</span></td>";
        	$cidlist.="</tr>\n";
    			$trunksOnCid[]=$trunk_id;
        }
      }
      if(!(is_array($trunksOnCid))) $cidlist="<tr id=\"tableintro\" bgcolor=\"#ffffff\"><td colspan=\"3\"></td><td colspan=\"3\">".T_("Caller ID is set to default for all lines")."</td></tr>";
      //create trunk list
    	$ret=$asterisk->getTrunk(0,0);
    	if (is_array($ret))
      foreach ($ret as $t) {
        $trunk_id=$t["id"];
        $trunk_name=$t["name"];
        $trunk_enable=$t["enable_cid"];
        if($trunk_enable==1){
    			if(is_array($trunksOnCid)){
            if (!(in_array($trunk_id,$trunksOnCid))) $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
          }
          else $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
        }
  		}
      //title
      $title=sprintf(T_("Edit Cid for extension %s"),$extension );
    }else header("location: ../");
  }else header("location: ../");

  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
    <div class="SectionHeader">
      <div id="loading" style="float: right;"></div>
      <h1><?=$title?></h1>
      <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
    </div>
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post">
        <!-- Cid -->
        <h2><?=T_("Caller ID")?></h2>
        <p class="blockintro"><?=T_("Set CID on outgoing lines")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="trunklist"><?=T_("Line")?>:</label></dt>
            <dd><select id="trunklist" name="trunklist"><?=$trunklist?></select><span> <img src="<?=$relBasePath?>/public/img/add.gif" alt="addCid" onclick=" addCidRow(); "/>&nbsp;<?=T_("add personal Caller ID for selected line")?></span></dd>
          </dl>
  				<table  id="stats" cellpadding="0" cellspacing="0">
  				  <tr><th></th><th><?=T_("CLIR")?></th><th><?=T_("Line")?></th><th><?=T_("CID Number")?></th><th><?=T_("CID Name")?></th><th><?=T_("Line Overwrite")?></th></tr>
  				  <span id="intable"><?=$cidlist?></span>
  				</table>
        </div>
        <!-- Buttons -->
        <div class="action">
          <?if ($_GET["id"]!="") {?> <input type="hidden" id="extension" name="extension" value="<?=$_GET['id']?>" /><?}?>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="document.getElementById('mainform').submit();"/></a>
        </div>
      </form>
    </div>

    <script>
      function addCidRow(){
        document.getElementById('alert').innerHTML='';
        var newRowIndex = (document.getElementById('stats').rows.length);
        var newRow = document.getElementById('stats').insertRow(newRowIndex);
        newRow.id = document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value + "_row";
        newRow.bgColor = "#ffffff";
        var newCell_0 = newRow.insertCell(0); newCell_0.id = newRow.id + "_cell0";
        var newCell_1 = newRow.insertCell(1); newCell_1.id = newRow.id + "_cell1";
        var newCell_2 = newRow.insertCell(2); newCell_2.id = newRow.id + "_cell2";
        var newCell_3 = newRow.insertCell(3); newCell_3.id = newRow.id + "_cell3";
        var newCell_4 = newRow.insertCell(4); newCell_4.id = newRow.id + "_cell4";
        var newCell_5 = newRow.insertCell(5); newCell_5.id = newRow.id + "_cell5";
        xajax_addCid(document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value);
      }
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="cid";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

